<?php
/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
*/

/**
 * Description of Select
 *
 * @author chaporgin_a
 */
class VA_Form_FormElement_Select extends VA_Form_FormElement {
    protected $selectOptions = array();
    const TYPE_MULTIPLE = 'multiple="multiple"';
    const TYPE_SINGLE = '';
    protected $type = null;
    public function  __construct() {
        parent::__construct();
        $this->value = array();
        $this->type = self::TYPE_SINGLE;
    }
    /**
     * Показываем что это - список со множественным выбором или с единственным
     * @param mixed $type
     * @return VA_Form_FormElement_Select
     */
    public function setSelectionType($type) {
        if(!in_array($type, array(self::TYPE_SINGLE,self::TYPE_MULTIPLE), TRUE))
            throw new Exception(sprintf('no such selection type: %s', $type));
        $this->type = $type;
        return $this;
    }
    public function getSelectionType() {
        return $this->type;
    }
    public function addValue($value) {
        if(!in_array($value, $this->value))
            $this->value[] = $value;
        return $this;
    }
    public function setOption($title, $value = null) {
        if(null === $value) $this->selectOptions[] = $title;
        else $this->selectOptions[$value] = $title;
        return $this;
    }
    public function getOptions() {
        return $this->selectOptions;
    }
    public function getPrintableValue() {
        $return = array();
        foreach ($this->getOptions() as $option => $name) {
            if(in_array($option, $this->value)) $return[] = $name;
        }
        return $return;
    }
    public function setValue($value) {
        if(!array_key_exists($value, $this->selectOptions))
            throw new Exception('trying to set non-existent value');
        if(!is_array($this->value)) $this->value = array($value);
        else if(!in_array($value, $this->value)) $this->value[] = $value;
        return $this;
    }
    /**
     * Функция для удобства
     * @param <type> $title
     * @return <type>
     */
    public function setValueByTitle($title) {
        if(!in_array($title, $this->selectOptions))
            throw new Exception('trying to set non-existent option');
        foreach(array_keys($this->selectOptions, $title) as $value)
            $this->setValue($value);
        return $this;
    }
    public function getHTMLTagAttribute($name, $onlyValue = FALSE) {
        if($name == 'name')
            return 'name="'.parent::getHTMLTagAttribute($name, TRUE).'[]"';
        return parent::getHTMLTagAttribute($name, $onlyValue);
    }
    public function ResetValue() {
        $this->value = array();
    }
}

